#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File ：UserModel.py
@Author ：zqy
@Email : zqingy@work@163.com
@note:
"""

from sqlalchemy import Column, Integer, String, ForeignKey, Text, UniqueConstraint
from sqlalchemy.orm import relationship

from application.util.MysqlUtil import mysql_db


class User(mysql_db.Model):
    __tablename__: str = "user"
    id = Column(Integer, primary_key=True, unique=True, autoincrement=True, comment="主键，自增")
    phone = Column(Integer, nullable=True, unique=True, comment="手机号码，长度为11")
    nickname = Column(String(8), nullable=True, comment="昵称，长度为8")
    username = Column(String(16), nullable=True, unique=True, comment="用户名，长度为16，唯一")
    password = Column(String(40), nullable=True, comment="密码，sha1(md5)，长度40")
    email = Column(String(32), default="", comment="邮箱，长度为32")
    avatar = Column(Text, default="", comment="头像URL")
    #
    addresses = relationship("Address", back_populates="user")
    cart_items = relationship("CartItem", back_populates="user")
    orders = relationship("Order", back_populates="user")
    points = relationship("UserPoints", back_populates="user")
    favorites = relationship("Favorite", back_populates="user", cascade="all, delete-orphan")
    roles = relationship("UserRoleModel", back_populates="user", cascade="all, delete-orphan")

    @property
    def role_names(self):
        return [i.role.name for i in self.roles]

    @property
    def is_superuser(self):
        return 'superuser' in self.role_names

class UserPoints(mysql_db.Model):
    __tablename__ = 'user_points'
    __table_args__ = {'comment': '用户积分表'}

    id = Column(Integer, primary_key=True, comment="积分记录ID")
    user_id = Column(Integer, ForeignKey('user.id'), comment="用户ID")
    points = Column(Integer, default=0, comment="当前积分")

    user = relationship("User", back_populates="points")


class Favorite(mysql_db.Model):
    __tablename__ = 'favorite'
    __table_args__ = (
        UniqueConstraint('user_id', 'product_id', name='_user_product_uc'),
    )

    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
    product_id = Column(Integer, ForeignKey('product.id'), nullable=False)

    user = relationship("User", back_populates="favorites")
    product = relationship("Product", back_populates="favorites")
